<template>
  <div v-loading="loading" class="padding" :style="styleObj" style="height: 100%;width:100%;">
    <div v-if="showCard" class="">
      <el-checkbox-group v-model="checked" class="padding-horizontal margin-top">
        <el-checkbox v-for="item in checkbox" :key="item.code" :label="item.code" style="margin-bottom: 10px;">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
    </div>
    <div v-if="showCard" class="flex flex-wrap" style="margin: 1em -0.5em 0 -.5em;">
      <div v-for="item in lists" :key="item.id" class="card-wrap">
        <div :class="{'is-warning': item.id === Infinity}" class="card-item" @click="clickCardItem(item)">
          <el-popover :width="300" trigger="hover">
            <ul class="card-item-ul">
              <li class="card-item-li">
                <span class="label">企业名称：</span>
                <span class="value">{{ item.enterpriseName }}</span>
              </li>
              <li class="card-item-li">
                <span class="label">所属行业：</span>
                <span class="value">{{ item.belongIndustryName }}</span>
              </li>
              <li class="card-item-li">
                <span class="label">所属地区：</span>
                <span class="value">{{ item.districtBelongName }}</span>
              </li>
              <li class="card-item-li">
                <span class="label">能耗水平：</span>
                <span class="value">{{ item.energyConsumptionLevelName }}</span>
              </li>
              <li class="card-item-li">
                <span class="label">联系人：</span>
                <span class="value">{{ item.principal }}</span>
              </li>
              <li class="card-item-li">
                <span class="label">联系电话：</span>
                <span class="value">{{ item.principalPhone }}</span>
              </li>
            </ul>
            <h3 slot="reference" class="card-item-title">{{ item.enterpriseName }}</h3>
          </el-popover>
        </div>
      </div>
    </div>
    <div v-if="showDetail" class="flex height-100">
      <div class="left-content dark-alpha-block height-100">
        <div class="padding bg-white select-wrap">
          <el-select v-model="selected" class="width-100" clearable filterable @change="onEnterpriseChange">
            <el-option
              v-for="option in lists" :key="option.id"
              :label="option.enterpriseName" :value="option.id"
            ></el-option>
          </el-select>
        </div>
        <el-scrollbar style="width: 100%;height:calc(100% - 60px);" wrap-style="overflow-x: hidden;">
          <enterprise-panel :info="enterpriseInfo"></enterprise-panel>
        </el-scrollbar>
      </div>
      <div class="right-content height-100">
        <el-scrollbar style="width: 100%;height:100%;" wrap-style="overflow-x: hidden;">
          <div class="grid-content">
            <grid-item-one :data="gridItemOneData"></grid-item-one>
            <real-time-curve height="300px" :data="realTimeCurveData"></real-time-curve>
            <grid-item-two :data="gridItemTwoData"></grid-item-two>
            <div class="two-cols" ref="fakeGapWrap">
              <grid-item-three
                v-for="(item, index) in gridItemOneData" :key="item.energyType"
                :energy-type="item.energyType" :color="colors[index % colors.length]"
              ></grid-item-three>
              <grid-item-six
                v-for="(item, index) in enterpriseReportData" :tooltip="tips[index]"
                :key="index" :data="item" :color="colors[index % colors.length]"
              ></grid-item-six>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script>
import EnterprisePanel from './enterprise-panel'
import GridItemOne from './grid-item-one'
import GridItemTwo from './grid-item-two'
import GridItemThree from './grid-item-three'

import GridItemSix from './grid-item-six'

import RealTimeCurve from './real-time-curve.vue'
import {
  loadEnterprise,
  loadUnderEnterprise as getListEnterprise
} from '@/api/enterprose'

import MixinGridItemOne from './mixin-grid-item-one'
import MixinRealTimeCurve from './mixin-real-time-curve'
import MixinGridItemTwo from './mixin-grid-item-two'
import MixinGridItemLast from './mixin-grid-item-last'

import mixinFakeGap from '@/mixins/mixin-fake-gap'

export default {
  name: 'energy-analysis',
  mixins: [MixinGridItemOne, MixinRealTimeCurve, MixinGridItemTwo, MixinGridItemLast, mixinFakeGap],
  components: {
    RealTimeCurve,
    EnterprisePanel,
    GridItemOne,
    GridItemTwo,
    GridItemThree,

    GridItemSix,
  },
  data () {
    return {
      selected: '',
      info: {},
      info1: [],
      info2: [],
      lists: [],
      loading: false,
      showCard: false,
      showDetail: false,
      checked: [],

      colors: [
        '#ffc107',
        '#28a745',
        '#fd7e14',
        '#6610f2',
        '#e83e8c',
      ]
    }
  },
  computed: {
    energyUnits () {
      return this.$store.state.energyUnits
    },
    energyVariety () {
      return this.$store.state.energyVariety
    },
    energyIndustry () {
      return this.$store.state.energyIndustry
    },
    isIndustry () {
      return !!this.$route.query.industryCode
    },
    districts () {
      return this.$store.getters['user/districts']
    },
    checkbox () {
      return this.isIndustry ? this.energyIndustry : this.districts
    },
    styleObj () {
      return this.showCard
        ? {
            'overflow-y': 'auto',
            'overflow-x': 'hidden',
          }
        : 'overflow: hidden;'
    },
    enterpriseInfo () {
      const {
        enterpriseName,
        districtBelongName,
        belongIndustryName,
        energyConsumptionLevelName,
        principal,
        principalPhone,
      } = this.info
      return [
        {
          name: '企业名称',
          value: enterpriseName || '-'
        },
        {
          name: '所在区域',
          value: districtBelongName || '-'
        },
        {
          name: '所属行业',
          value: belongIndustryName || '-',
        },
        {
          name: '能耗规模',
          value: energyConsumptionLevelName || '-'
        },
        {
          name: '能耗在线监测设备情况',
          value: '-'
        },
        {
          name: '能源管理岗位备案情况',
          value: '-'
        },
        {
          name: '节能项目备案情况',
          value: '-'
        },
        {
          name: '联系人',
          value: principal || '-',
        },
        {
          name: '联系方式',
          value: principalPhone || '-'
        },
      ]
    },
  },
  updated () {
    const wrap = this.$refs.fakeGapWrap;
    if (wrap) {
      const els = Array.from(wrap.querySelectorAll('.content-block'));
      els.forEach((el, index) => {
        if (index % 2 !== 0) {
          this.fixFakeGap('marginLeft', el)
        }
        if (index > 1) {
          this.fixFakeGap('marginTop', el)
        }
      })
    }
  },
  watch: {
    // 企业ID
    '$route.query.enterpriseCode': function (val) {
      this.watchHandler()
    },
    checked () {
      this.queryLists()
    },
  },
  mounted () {
    this.$store.dispatch('user/getDistrictsList')
    if (this.isIndustry) {
      this.$store.dispatch('GET_ENERGY_INDUSTRY')
    }
    this.watchHandler()
    this.loadEnterpriseDetailsEnergyData()
  },
  methods: {
    // NOTE:为了兼容新老接口
    getEnterpriseIdByEnterpriseCode (enterpriseCode) {
      const lists = this.lists;
      const target = lists.find(item => item.id === enterpriseCode);
      return target ? target.enterpriseId : null;
    },
    loadEnterpriseDetailsEnergyData () {
      this.getGridItemOneData();
      this.getRealTimeCurveData();
      this.getGridItemTwoData();
      this.getEnterpriseReportData();
    },
    watchHandler () {
      const {
        industryCode,
        enterpriseCode,
        districtCode
      } = this.$route.query
      if (!enterpriseCode) {
        if (this.isIndustry) {
          this.checked = industryCode ? String(industryCode).split(',') : []
        } else {
          this.checked = districtCode ? String(districtCode).split(',') : []
        }
        this.showCard = true
        this.showDetail = false
        this.queryLists()
      } else {
        this.selected = this.enterpriseCode = Number(enterpriseCode)
        this.showCard = false
        this.showDetail = true
        this.queryLists()
        this.getDetails()
      }
    },
    queryLists () {
      this.loading = true
      const key = this.isIndustry ? 'belongIndustry' : 'districtBelong'
      const params = {
        [key]: this.checked.length ? this.checked.join(',') : '',
      }
      return getListEnterprise(params).then(res => {
        if (res.code === 200) {
          this.lists = res.data
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getDetails () {
      const enterpriseCode = this.$route.query.enterpriseCode;
      if (enterpriseCode) {
        this.getEnterpriseInfo(enterpriseCode)
      }
    },
    getEnterpriseInfo (enterpriseCode) {
      return loadEnterprise(enterpriseCode).then(res => {
        if (res.code === 200) {
          this.info = res.data
        }
      })
    },
    clickCardItem (item) {
      this.$router.push({
        path: '/redirect' + this.$route.path,
        query: {
          enterpriseCode: item.id,
          enterpriseId: item.enterpriseId
        }
      })
      this.showCard = false
      this.getDetails()
      this.showDetail = true
    },
    onEnterpriseChange () {
      this.enterpriseCode = this.selected
      const enterprise = this.lists.find(item => item.id === this.selected)
      const enterpriseId = enterprise ? enterprise.enterpriseId : ''
      let fullpath = this.$route.fullPath
      fullpath = fullpath.replace(/(enterpriseCode=)([a-zA-Z0-9]+)/, '$1' + this.enterpriseCode)
      fullpath = fullpath.replace(/(enterpriseId=)([a-zA-Z0-9-]+)/, '$1' + enterpriseId)
      // console.log(fullpath)
      fullpath = '/redirect' + fullpath
      this.$router.replace(fullpath).catch(() => {
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/style/variable.scss";

.card-wrap {
  flex: 0 0 25%;
  padding: 0 .5em;
  overflow: hidden;
}

.card-item {
  background: white;
  padding: 1.5rem 1rem;
  margin-bottom: 1em;
  border-radius: .3em;
  cursor: pointer;
  transition: all .3s;
  //
  //&:hover {
  //  box-shadow: 0 .25rem 1rem rgba(0, 0, 0, 0.2);
  //}
  &.is-warning {
    background: #dc3545;
    color: white;
  }
}

.card-item-title {
  margin: 0;
  text-align: center;
}

.card-item-ul {
  list-style: none;
  padding-left: 0;
  margin-bottom: 0;
  margin-top: .5em;
  font-size: 12px;
  line-height: 1.8;

  .label {
    color: #909399;
  }

}

.card-item-title,
.card-item-li {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.left-content {
  width: 400px;
  flex-shrink: 0;
  transition: width .3s;
  @media screen and (max-width: 1330px) {
    width: 300px;
  }
}

.right-content {
  flex: 1;
  margin-left: $gutter;
  width: calc(100% - 500px - $gutter);
}

.grid-content {
  & > .content-block {
    margin-top: $gutter;
    &:first-child {
      margin-top: 0;
    }
  }
  .two-cols {
    display: flex;
    flex-wrap: wrap;
    gap: $gutter;
    margin-top: $gutter;
    & > .content-block {
      width: calc((100% - $gutter) / 2);
    }
  }
  ::v-deep .info-head {
    padding: 20px $gutter 0 $gutter;
    font-size: 16px;
  }

  .content-block {
    background: white;
    border-radius: 4px;
  }
}
::v-deep .date-picker {
  width: 100px !important;
  margin-left: auto;
}
::v-deep .date-picker .el-input__inner {
  background: transparent;
  border: none;
  padding-right: 0 !important;
}
</style>
